package com.example.demo.controller;

import com.auth0.jwt.JWT;
import com.example.demo.ServerResponse;
import com.example.demo.Service.UserService;
import com.example.demo.entity.User;
import com.example.demo.entity.VO.LoginUser;
import com.example.demo.utils.JWTUtils;
import com.example.demo.utils.PassToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
public class TestController {
    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @PostMapping("/login")
    public ServerResponse login(@RequestBody LoginUser loginUser){
        //先判断验证码是否正确
        //1.如何从redis获取保存的验证码
        String storeCode = (String) redisTemplate.opsForValue().get("captcha_codes:"+loginUser.getUuid());
        System.out.println(storeCode+loginUser.toString());
        //2.
        if (loginUser.getCode().equals(storeCode)){
            User u =userService.getUser(loginUser);
            if(u!=null){
                Map<String,String> map =new HashMap<>();
                map.put("username",u.getUserName()+"");
                map.put("userid",u.getUserId()+"");
                String token = JWTUtils.getToken(map);
                redisTemplate.delete(storeCode);
                return ServerResponse.createBySuccess(200,token,"登录成功");
            }
            return ServerResponse.createBySuccess(500,"","账号或密码错误");
        }else {
            return ServerResponse.createBySuccess(500,"","验证码错误");
        }
    }

    @PassToken
    @GetMapping("/getStudents")
    public  ServerResponse<String> getStudents(){
        return ServerResponse.createBySuccess(200,"","查询成功");
    }

    @GetMapping("/getInfo")
    public ServerResponse<User> getinfo(HttpServletRequest request){
        String token= request.getHeader("Authorization");
        System.out.println("我是token:"+token);
        String id = JWT.decode(token.substring(token.lastIndexOf(" ")+1)).getClaim("userid").asString();
        User user = userService.getUserById(Integer.parseInt(id));
        return ServerResponse.createBySuccess(200,user,"查询成功");
    }

    @PassToken
    @GetMapping("/getBanners")
    public ServerResponse<List<String>> getBanners(){
        List<String> list = new ArrayList<>();
        list.add("/images/1.webp");
        list.add("/images/2.webp");
        list.add("/images/3.webp");
        return ServerResponse.createBySuccess(200,list,"显示轮播图");
    }
}